package com.atguigu.flink.chapter07_state;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * Created by Smexy on 2022/10/28
 *
 * 计算每个传感器的水位和
 *
 *
 */
public class Demo7_ReducingState
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           .keyBy(WaterSensor::getId)
           .process(new KeyedProcessFunction<String, WaterSensor, String>()
           {

               private ReducingState<Integer> vc;

               //task启动时，只执行一次。 获取状态
               @Override
               public void open(Configuration parameters) throws Exception {

                   vc = getRuntimeContext().getReducingState(new ReducingStateDescriptor<Integer>("vc", new ReduceFunction<Integer>()
                   {
                       @Override
                       public Integer reduce(Integer value1, Integer value2) throws Exception {
                           return value1 + value2;
                       }
                   }, Integer.class));

               }

               /*
                                   WaterSensor value: 当前数据
                               */
               @Override
               public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                    vc.add(value.getVc());

                   out.collect(ctx.getCurrentKey() + "累积水位:" +vc.get());
                   out.collect(value.toString());

               }
           }).print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
